package cn.itcast.controller;

import cn.itcast.common.R;
import cn.itcast.entity.Employee;
import cn.itcast.entity.Page;
import cn.itcast.service.IEmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

import static cn.itcast.common.R.success;

@RestController
@Slf4j
@RequestMapping("employee")
public class EmployeeController extends BaseController{
        @Autowired
     private IEmployeeService employeeService;

    /**
     * 登录
     * @param employee
     * @return
     */
    @PostMapping("login")
        public R<Employee> login(@RequestBody Employee employee){
            R<Employee> rs = employeeService.login(employee);

            if (rs.getCode() == 1){
                session.setAttribute("LOGIN_ID",rs.getData().getId());
                session.setMaxInactiveInterval(10*60);//测试用，正式记得关闭！
            }
           return  rs;

         }
         //登出
         @PostMapping("logout")
    public R<String> logout(){
             session.invalidate();
             return success("success");

         }

         //添加员工
    @PostMapping
    public R<String> save(@RequestBody Employee employee){
      /*  employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateUser(((Long) session.getAttribute("LOGIN_ID")));
        employee.setUpdateUser(((Long) session.getAttribute("LOGIN_ID")));*/
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes(StandardCharsets.UTF_8)));
        employeeService.save(employee);

        log.info("添加员工:{}成功",employee.getName());

        return success("添加成功");

    }

    /**
     * 分页查询员工
     */
   @GetMapping("page")
    public R<Page<Employee>> page(Integer page,Integer pageSize,String name) {
        Page<Employee> pageInfo =employeeService.findByPage(page,pageSize,name !=null ? name.trim():name);
        return success(pageInfo);
    }

    /**
     * 启用、禁用状态切换
     */
    @PutMapping
    public R<String> update(@RequestBody Employee employee){
        /*employee.setUpdateUser(findIdFromSession());
        employee.setUpdateTime(LocalDateTime.now());*/
        employeeService.update(employee);
        return success("修改成功");
    }
    /**
     *
     *编辑信息回显
     */
    @GetMapping("/{id}")
    public R<Employee> edit(@PathVariable Long id){
        log.info("id:"+id);
       Employee employee = employeeService.findById(id);
       return success(employee);
    }
}
